package com.woniuxy.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.entity.AllShop;
import com.woniuxy.mapper.ShopMapper;
import com.woniuxy.service.ShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author hq
 * @Date 2025/7/22$ 15:45$
 * @Description TODO
 * @Params $
 * @Return $
 **/
@Service
public class ShopServiceImpl implements ShopService {

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String CACHE_KEY_PREFIX = "search_product:";
    private final ObjectMapper objectMapper = new ObjectMapper();

    // 搜索商品
    @Override
    public List<AllShop> search(String keyword) {
        String cacheKey = CACHE_KEY_PREFIX + keyword;

        // 1. 先从 Redis 中获取缓存数据
        String cachedJson = redisTemplate.opsForValue().get(cacheKey);
        if (cachedJson != null && !cachedJson.isEmpty()) {
            try {
                return objectMapper.readValue(cachedJson, objectMapper.getTypeFactory().constructCollectionType(List.class, AllShop.class));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // 2. 缓存未命中，查询数据库
        List<AllShop> products = shopMapper.search(keyword);

        // 3. 将结果写入 Redis 缓存，设置过期时间（例如 5 分钟）
        if (products != null && !products.isEmpty()) {
            try {
                String json = objectMapper.writeValueAsString(products);
                redisTemplate.opsForValue().set(cacheKey, json, 5, TimeUnit.MINUTES);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
        return products;
    }

    // 获取商品详情
    @Override
    public AllShop getById(Integer shopId) {
        return shopMapper.selectById(shopId);
    }
    // 获取商品价格区间
    @Override
    public List<AllShop> getProductsByPriceRange(Integer minPrice, Integer maxPrice) {
        return shopMapper.getProductsByPriceRange(minPrice, maxPrice);
    }

}
